<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of owlcourse
 *
 * @author trung
 */
class Owl_Course extends Owl_Db{
    
    function Owl_Course(){
        $this->Owl_Db('course');
    }

    function get_all_courses(){
        return $this->get_results('//course');
    }

    function get_all_documents($num = 5) {
        return array_slice(array_reverse((array)$this->get_results('//document')), 0, $num);
    }

    function get_course($nice_url) {
         if ( empty($nice_url) )
            return false;
        return $this->get_row('/courses/course[nice_url="'.$nice_url.'"]');
    }

    function get_documents_for_rss() {
        return array_slice(array_reverse((array)$this->get_results('//document')), 0, get_option("content_per_page", 10));
    }
    
    function insert_course($data) {
        if ( trim( $data['nice_url'] ) == "" ) {
            $this->last_error = new Owl_Error('502',__('Invalid course name'));
            return false;
        }
        if ($this->get_course($data['nice_url']) !== false ){
            $this->last_error = new Owl_Error('502',__('Course name is duplicate'));
            return false;
        }
        $defaults = array(
                            'name' => '',
                            'level' => 'Đại học',
                            'unit' => 4,
                            'description' => '',
                            'nice_url' => Owl_Format::make_file_name($data['name']),
                            'documents' => array()                            
                        );
                        
        $data = Owl_System_Helper::array_merge($data, $defaults);
        return $this->insert('/courses', 'course', $data);
    }

    function delete_course($nice_url) {
        if ( empty($nice_url) )
            return false;
        if ($this->has_document($nice_url)) {
            $this->last_error = new Owl_Error('502', __('Cannot delete this course because it has documents! Please delete its documents first!'));
            return false;
        }
        return $this->delete('/courses/course[nice_url="'.$nice_url.'"]');
    }

    function has_document($nice_url) {
        $course = $this->get_course($nice_url);
        return ($course && is_array($course["documents"]));
    }

    function update_course($nice_url, $data){
        if ( empty($nice_url) )
            return false;

        $old_course = $this->get_course($nice_url);

        if ($old_course === false){
            $this->last_error = new Owl_Error('502','Course is not exist');
            return false;
        }

        $defaults = array(
                            'name' => $old_course['name'],
                            'level' => $old_course['level'],
                            'unit' => $old_course['unit'],
                            'description' => $old_course['description'],
                            'nice_url' => $old_course['nice_url'],
                            'documents' => $old_course['documents']
                        );
        $data = Owl_System_Helper::array_merge($data, $defaults);
        $data = Owl_Format::esc_html_deep($data);
        
        return $this->update('/courses/course[nice_url="'.$nice_url.'"]','course',$data);
    }
    
    function insert_document($nice_url, $document_name, $document_link, $document_type){
        if (empty ($nice_url) || empty ($document_link) || empty ($document_name)){
            return false;
        }
        if ($this->get_row('/courses/course[nice_url="'.$nice_url.'"]/documents/document[name="'.$document_name.'"]', false) === false)
            return $this->insert('/courses/course[nice_url="'.$nice_url.'"]/documents', 'document', array('name' => "$document_name",'link'=>"$document_link", "type"=>"$document_type"));
        else {
            $this->last_error= new Owl_Error("502", __("Document is duplicate"));
            return false;
        }
            
    }

    function get_document($nice_url, $document_name) {
        $course = $this->get_course($nice_url);
        if (!$course) {
            return false;
        }
        foreach ($course["documents"] as $document) {
            if ($document["name"] == $document_name) {
                return $document;
            }
        }
        return false;
    }

    function update_document_name($nice_url, $old_name, $new_name) {
        if (empty ($nice_url) || empty ($old_name) || empty ($new_name)){
            return false;
        }
        $old_document = $this->get_document($nice_url, $old_name);
        if ($old_document == false) {
            $this->last_error = new Owl_Error('502', __('Document does not exist'));
            return false;
        }
        if ($this->get_document($nice_url, $new_name)) {
            $this->last_error = new Owl_Error('502', __('Document is duplicate'));
            return false;
        }
        $defaults = array(
                            'name' => $old_document['name'],
                            'type' => $old_document['type'],
                            'link' => $old_document['link']
                        );
        $data = array('name' => $new_name);
        $data = Owl_System_Helper::array_merge($data, $defaults);
        
        return $this->update('/courses/course[nice_url="'.$nice_url.'"]/documents/document[name="'.$old_name.'"]','document',$data);
    }
    
    function delete_document($nice_url, $document_name){
        if (empty ($nice_url) || empty ($document_name)){
            return false;
        }
        $old_document = $this->get_document($nice_url, $document_name);
        if ($this->delete('/courses/course[nice_url="'.$nice_url.'"]/documents/document[name="'.$document_name.'"]')) {
            return $old_document;
        }
        else {
            return false;
        }
    }
    
    function update_list_document($nice_url, $data = array()){
        if ($nice_url || empty ($data)){
            return false;
        } else {
            return $this->update('/courses/course[nice_url="'.$nice_url.'"]/documents','documents', $data);
        }
    }

    function get_course_with_lang($nice_url, $lang) {
        $course = $this->get_course($nice_url);
        if ($course == false) {
            return false;
        }
        $owl_ulang = new Owl_Ulang();
        $name_translator = $owl_ulang->get_ulang($course["name"]);
        if ($name_translator == false) {
            return false;
        }
        $name_translated = ($name_translator[$lang]) ? $name_translator[$lang] : "" ;
        $description_translator = $owl_ulang->get_ulang($course["description"]);
        if ($description_translator == false) {
            return false;
        }
        $description_translated = ($description_translator[$lang]) ? $description_translator[$lang] : "";
        return array($name_translated, $description_translated);
    }

    function get_max_id() {
        $courses = $this->get_all_courses();
        $name = array();
        foreach($courses as $course) {
            $name[] = $course["name"];
        }
        array_multisort($name, SORT_DESC, $courses);
        $max_name = explode(" ", $courses[0]["name"]);
        return ($max_name[1] + 1);
    }

    function to_json($args = array()) {
        $page = 1;
        $admin = false;
        extract($args);

        $data = array();
        $courses = $this->get_all_courses();
        if ($courses === false) {
            $data["code"] = 0;
            $data["message"] = $this->get_error();
        }
        else {
            //Paging
            $total = count($courses);
            $page_boundary = Owl_Functions::get_pagination_boundary($page, $total);

            if ($page_boundary !== false) {
                $data["code"] = 1;
                $data["message"] = "Success";
                $data["total"] = ceil($total / get_option("content_per_page", 15));

                list($begin, $end) = $page_boundary;
                $data["hasTab"] = false;
                $data["hasHeader"] = true;
                $data["rows"] = array();

                //Fetch content
                for ($i = $begin; $i <= $end; $i++) {
                    $course = $courses[$i];
                    $row = array();
                    $row["header"] = '<span>' . Owl_Format::esc_html(__($course["name"], true)) . '</span>';
                    $row["content"][] = "<b>" . __("Course name") . "</b>: " .  Owl_Format::esc_html(__($course["name"], true));
                    $row["content"][] = "<b>" . __("Course level") . "</b>: " . __($course["level"]);
                    $row["content"][] = "<b>" . __("Course unit") . "</b>: " . $course["unit"];
                    $row["content"][] = "<b>" . __("Description") . "</b>: " . Owl_Format::make_nice_textarea_content(Owl_Format::esc_html(__($course["description"], true)));

                    $row["content"][] = Owl_Format::convert_document($course["documents"]);

                    if ($args["admin"]) {
                        $row["form"][__("Edit")] = $this->build_form($course, $i);
                    }
                    $data["rows"][] = $row;
                }
            }
            else {
                $data["code"] = 0;
                $data["message"] = __("No data");
            }
            $data["controlText"] = Owl_Functions::get_control_text();
            return Owl_Functions::json_encode($data);
        }
        
    }

    function build_form($course = array(), $pos = false, $show_link = true) {
        if (empty($course)) {
            $string = '';
        }
        else {
            $string = '<div class="form-container">';
        }
        if (empty($course)) {
            $string .= '<form action="' . Owl_Link::ajax_url(false) . 'course-ajax.php" method="POST" id="course-add">';
        }
        else {
            $string .= '<form action="' . Owl_Link::ajax_url(false) . 'course-ajax.php" method="POST" id="course-edit-' . $pos . '">';
        }

        if (empty($course)) {
            $string .= Owl_Form::print_hidden(array(
                "name" => "action",
                "value" => "add_course",
                "toString" => true
            ));
        }
        else {
            $string .= Owl_Form::print_hidden(array(
                "name" => "nice_url",
                "value" => $course["nice_url"],
                "id" => "course-hidden-" . $pos,
                "toString" => true
            ));
            $string .= Owl_Form::print_hidden(array(
                "name" => "action",
                "value" => "edit_course",
                "toString" => true
            ));
        }
        $string .= '<table class="form-table" border="0" cellspacing="0" cellpadding="0">';
        $string .= '<tbody>';

        //Language
        $string .= '<tr>';
        $string .= '<th>';
        $string .= Owl_Form::print_label(array(
            'value' => __("Language"),
            'toString' => true
        ));
        $string .= '</th>';
        $string .= '<td>';
        if (empty($course)) {
            $string .= Owl_Form::print_combo_box(array(
                'name' => 'lang',
                'value' => get_current_language(),
                'options' => Owl_Functions::get_available_languages(),
                'toString' => true
            ));
        }
        else {
            $string .= Owl_Form::print_combo_box(array(
                'name' => 'lang',
                'value' => get_current_language(),
                'options' => Owl_Functions::get_available_languages(),
                'class' => 'form-combobox input-lang-changer',
                'toString' => true
            ));
        }
        $string .= '</td>';
        $string .= '</tr>';

        //Name
        $string .= '<tr>';
        $string .= '<th>';
        $string .= Owl_Form::print_label(array(
            'value' => __("Course name"),
            'required' => true,
            'toString' => true
        ));
        $string .= '</th>';
        $string .= '<td>';
        $string .= Owl_Form::print_textbox(array(
            'name' => 'course_name',
            'value' => trim(Owl_Format::esc_html(__($course["name"], true, true))),
            'class' => 'form-textbox ' . Owl_Functions::build_validate_string(array('required')),
            'toString' => true
        ));
        $string .= '</td>';
        $string .= '</tr>';

        //Level
        $string .= '<tr>';
        $string .= '<th>';
        $string .= Owl_Form::print_label(array(
            'value' => __("Course level"),
            'toString' => true
        ));
        $string .= '</th>';
        $string .= '<td>';
        $string .= Owl_Form::print_combo_box(array(
            'name' => 'course_level',
            'value' => $course["level"],
            'options' => array(
                'College' => __("College"),
                'University' => __("University"),
                'Graduated' => __("Graduated")
            ),
            'toString' => true
        ));
        $string .= '</td>';
        $string .= '</tr>';

        //Unit
        $string .= '<tr>';
        $string .= '<th>';
        $string .= Owl_Form::print_label(array(
            'value' => __("Course unit"),
            'required' => true,
            'toString' => true
        ));
        $string .= '</th>';
        $string .= '<td>';
        $string .= Owl_Form::print_textbox(array(
            'name' => 'course_unit',
            'value' => $course["unit"],
            'class' => 'form-textbox ' . Owl_Functions::build_validate_string(array('required')),
            'toString' => true
        ));
        $string .= '</td>';
        $string .= '</tr>';

        //Description
        $string .= '<tr>';
        $string .= '<th>';
        $string .= Owl_Form::print_label(array(
            'value' => __("Description"),
            'toString' => true
        ));
        $string .= '</th>';
        $string .= '<td>';
        $string .= Owl_Form::print_textarea(array(
            'name' => 'course_description',
            'rows' => 5,
            'value' => trim(Owl_Format::esc_html(__($course["description"], true, true))),
            'class' => 'form-textarea',
            'toString' => true
        ));
        $string .= '</td>';
        $string .= '</tr>';
        

        //Ajax feedback
        $string .= '<tr>';
        $string .= '<td colspan="2">';
        $string .= '<div class="ajax-feedback">';
        $string .= '<div class="ajax-message"></div>';
        $string .= '</div>';
        $string .= '</td>';
        $string .= '</tr>';

        //Button
        $string .= '<tr>';
        $string .= '<td class="form-button-pane" colspan="2">';
        $string .= '<img src="' . Owl_Link::image_url(false) . 'default/ajax-load.gif" class="ajax-load" alt="Ajax load" />';
        if (empty($course)) {
            $string .= Owl_Form::print_button(array(
                'name' => 'add_course',
                'value' => __('Add'),
                'class' => 'form-button course-add-ajax-submit',
                'toString' => true
            ));
            $string .= Owl_Form::print_button(array(
                'type' => 'reset',
                'name' => 'cancel',
                'value' => __('Cancel'),
                'class' => 'form-button course-add-cancel',
                'toString' => true
            ));
        }
        else {
            $string .= Owl_Form::print_button(array(
                'name' => 'edit-course-' . $pos,
                'value' => __('Save'),
                'class' => 'form-button course-edit-ajax-submit',
                'toString' => true
            ));
            if ($show_link) {
                $string .= Owl_Form::print_button(array(
                    'name' => 'delete-course-' . $pos,
                    'value' => __('Delete'),
                    'class' => 'form-button course-delete-ajax-submit',
                    'toString' => true
                ));
            }
            $string .= Owl_Form::print_button(array(
                'type' => 'reset',
                'name' => 'cancel',
                'value' => __('Cancel'),
                'class' => 'form-button course-edit-cancel',
                'toString' => true
            ));
            if ($show_link) {
                $string .= '<a href="' . Owl_Link::template_url('documents-manager', false, array('var'=>$course["nice_url"])) . '" class="form-button">' . __("Add documents") . '</a>';
            }
        }
        $string .= '</td>';
        $string .= '</tr>';

        $string .= '</tbody>';
        $string .= '</table>';
        $string .= "</form>\n";
        if (!empty($course)) {
            $string .= "</div>\n";
        }
        return $string;
    }

    function print_course_dropdown($value = null) {
        echo '<select id="course-dropdown" name="course" >' . "\n";
        $this->print_course_dropdown_data($value);
        echo '</select>' . "\n";
    }

    function print_course_dropdown_data($value = null) {
        $courses = $this->get_all_courses();
        if ($value == 'last') {
            $value = $courses[count($courses)-1]["nice_url"];
        }
        foreach ($courses as $course) {
            if ($course["nice_url"] == $value) {
                echo '<option value="' . $course["nice_url"] . '" selected="selected">' . __($course["name"], true) . '</option>' . "\n";
            }
            else {
                echo '<option value="' . $course["nice_url"] . '">' . __($course["name"], true) . '</option>' . "\n";
            }
        }
    }

    function print_documents_table($course, $nice_url) {
        if (!is_array($course["documents"])) {
?>
<tr>
    <td colspan="3">
        <?php echo __("No data"); ?>
    </td>
</tr>
<?php
        }
        else {
            foreach($course["documents"] as $pos=>$document) {
?>
<tr>
    <td class="selectable" title="<?php echo __("Click to select, shift click to select multiple row, click again to edit") ?>">
        <div class="document-name"><?php echo Owl_Format::trim_text(Owl_Format::decode_xml($document["name"]), 40); ?></div>
        <div class="document-edit-form to-toggle">
            <form action="<?php Owl_Link::ajax_url() ?>course-ajax.php" method="POST" id="document-edit-<?php echo $pos ?>">
                <?php
                    Owl_Form::print_hidden(array(
                        'name' => 'action',
                        'value' => 'edit_document'
                    ));
                    Owl_Form::print_hidden(array(
                        'name' => 'nice_url',
                        'value' => $nice_url
                    ));
                    Owl_Form::print_hidden(array(
                        'name' => 'old_name[' . $pos .']',
                        'value' => $document['name'],
                        'class' => 'old-name-hidden'
                    ));
                    Owl_Form::print_textbox(array(
                        'name' => 'document_name[' . $pos . ']',
                        'value' => Owl_Format::decode_xml($document['name']),
                        'class' => 'form-textbox ' . Owl_Functions::build_validate_string(array('required'))
                    ));
                    Owl_Form::print_button(array(
                        'name' => 'submit',
                        'value' => __('Save'),
                        'class' => 'form-button document-edit-ajax-submit',
                        'title' => 'document-edit-' . $pos
                    ));
                    Owl_Form::print_button(array(
                        'type' => 'reset',
                        'name' => 'cancel',
                        'value' => __('Cancel'),
                        'class' => 'form-button document-edit-cancel',
                        'title' => 'document-edit-' . $pos
                    ));
                    Owl_Default_Content::print_ajax_feedback();
                ?>
            </form>
        </div>
    </td>
    <td>
        <?php echo '<span class="' . strtolower($document["type"]) . '">' . __(ucwords($document["type"])) . '</span>'; ?>
    </td>
    <td>
        <?php echo '<span class="download"><a href="' . Owl_Link::site_url(false) . $document["link"] .'">' . __("Download") . "</a></span>"; ?>
    </td>
</tr>
<?php
            }
        }
    }

    function print_document_form($nice_url) {
        echo '<form action="'.Owl_Link::ajax_url(false).'course-ajax.php" method="POST" id="document-add" enctype="multipart/form-data">';

        Owl_Form::print_hidden(array(
            "name" => "action",
            "value" => "add_document"
        ));

        Owl_Form::print_hidden(array(
            "name" => "nice_url",
            "value" => $nice_url
        ));

        echo '<table class="form-table" border="0" cellspacing="0" cellpadding="0">';
        echo '<tbody>';

        //Name
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __("Document's name"),
            'required' => true
        ));
        echo '</th>';
        echo '<td>';
        Owl_Form::print_textbox(array(
            'name' => 'document_name',
            'class' => 'form-textbox ' . Owl_Functions::build_validate_string(array('required'))
        ));
        echo '</td>';
        echo '</tr>';

        //File
        echo '<tr>';
        echo '<th>';
        Owl_Form::print_label(array(
            'value' => __("File to upload")
        ));
        echo '</th>';
        echo '<td>';
        Owl_Form::print_file_select(array(
            'name' => 'document_link',
            'description' => sprintf(__("Max file size: %s"), ini_get('upload_max_filesize'))
        ));
        echo '</td>';
        echo '</tr>';

        //Ajax feedback
        echo '<tr>';
        echo '<td colspan="2">';
        Owl_Default_Content::print_ajax_feedback(false);
        echo '</td>';
        echo '</tr>';

        echo '<tr>';
        echo '<td class="form-button-pane" colspan="2">';
        echo '<img src="' . Owl_Link::image_url(false) . 'default/ajax-load.gif" class="ajax-load" alt="Ajax load" />';
        Owl_Form::print_button(array(
            'name' => 'submitForm',
            'value' => __('Save'),
            'class' => 'form-button document-add-ajax-submit',
            'title' => 'document-add'
        ));
        Owl_Form::print_button(array(
            'type' => 'reset',
            'name' => 'cancel',
            'value' => __('Cancel'),
            'class' => 'form-button document-add-cancel',
            'title' => 'document-add'
        ));
        

        echo '</tbody>';
        echo '</table>';
        echo "</form>\n";
    }

    function to_rss() {
        $rss_data = $this->get_documents_for_rss();
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<rss version="2.0">' . "\n";
        echo '<channel>' . "\n";
        echo '<title>' . Owl_Format::esc_html(get_option('site_name')) . ' - ' . __("Documents") . '</title>' . "\n";
        echo '<link><![CDATA[' . "http://" . $_SERVER["HTTP_HOST"] . Owl_Link::template_url("course", false) . ']]></link>' . "\n";
        echo '<description>' . sprintf(__("Documents from %s"), Owl_Format::esc_html(get_option('site_name'))) . '</description>' . "\n";
        if (!empty ($rss_data)) {
            foreach ($rss_data as $item) {
                echo '<item>'."\n";
                echo '<title><![CDATA[' . Owl_Format::esc_html($item["name"]) .']]></title>'."\n";
                echo '<link><![CDATA[' . "http://" . $_SERVER["HTTP_HOST"] . Owl_Link::site_url(false) .  $item["link"] . ']]></link>'."\n";
                echo '</item>'."\n";
            }
        }
        echo '</channel>' . "\n";
        echo '</rss>';
    }
}

